#' 把U5_mr的res变成TSMR的res
#'
#' @param res U5_mr分析出的res
#'
#' @return TSMR的res
#' @export
#'
#' @examples
#'
#' \dontrun{
#'
#' TSMR_res<-U6_res_to_TSMR_res(res)
#'
#' }
#'
U6_res_to_TSMR_res<-function(res){
  long_ress <- res %>%
    split(list( .$id.exposure , .$id.outcome)  )

  long_ress <- Filter(function(x){ nrow(x) > 0} , long_ress)

  long_ress <- long_ress %>%
    furrr::future_map_dfr( res_to_long_res,.options = furrr::furrr_options(seed = TRUE),.progress = TRUE
    )
  return(long_ress)
}

res_to_long_res<-function(res=res){

  mr_res <- res %>% dplyr::select(c("id.exposure", "id.outcome",
                                    "outcome",     "exposure", "nSNP",
                                    dplyr::starts_with( c("b_","se_","pval_")) )
  )


  method<- mr_res %>% dplyr::select( dplyr::starts_with("b_") ) %>% colnames()

  method <- gsub("b_", "", method)

  mr_res_longs<-c()

  for (i in 1:length(method)) {
    mr_res_long <- mr_res %>% dplyr::select(c("id.exposure", "id.outcome",
                                              "outcome",     "exposure", "nSNP",
                                              dplyr::ends_with( method[i] )))
    colnames(mr_res_long)<- c("id.exposure","id.outcome","outcome", "exposure",
                              "nsnp","b", "se" ,  "pval" )
    mr_res_long$method<-method[i]
    mr_res_long<-mr_res_long[,c(1:4,9,5:8)]
    mr_res_longs<- plyr::rbind.fill(mr_res_longs,mr_res_long)
  }

  if("Wald ratio" %in% mr_res_longs$method ){
    if(!mr_res_longs$nsnp[which(mr_res_longs$method=="Wald ratio")]==1 )
     mr_res_longs<- mr_res_longs[-which(mr_res_longs$method=="Wald ratio"),]
  }

  if("MR_PRESSO" %in% mr_res_longs$method){
    mr_res_longs$nsnp[which(mr_res_longs$method=="MR_PRESSO")] = res$nsnp_MR_PRESSO
  }

  return(mr_res_longs)

}
